<?php

require_once('class.phpmailer.php');//引入类库文件

class UserController extends Controller
{
    /*
    * 获取列表分页
    *
    */
    public function actionGetListPaging()
    {

        try {
            //参数验证

            //检测
            //$user_id = SessionService::getUserIDBySessionid();


            $searchsql = Util::initSearchSql();


            //获取count
            $totalcount = UcUser ::model()->count($searchsql);

	            //排序
	            $searchsql = $searchsql . " order by create_time  desc";

	            //加上分页控制
	            $searchsql = Util::addLimitSql($searchsql);

	            //获取list
	            $list = UcUser ::model()->findAll($searchsql);


	            Util::responseList($totalcount, $list);

	        } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }


    }

    /*
    * 添加
    *
    */
    public function actionAdd()
    {

        try {
            //检测
           // $user_id = SessionService::getUserIDBySessionid();

            //参数验证
            $name = Util::getParamNotEmpty("name");
            $target_weight = Util::getParamNotEmpty("target_weight");



            //添加
            $obj = new UcUser();
            Util::initObjData($obj);


            $obj->name = $name;
            $obj->target_weight = $target_weight;


            Util::saveObjData($obj);


            //返回数据
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


        } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
    * 添加
    *
    */
    public function actionAddWeight()
    {

        try {
            //检测
            //$user_id = SessionService::getUserIDBySessionid();

            //参数验证
            $user_id = Util::getParamNotEmpty("user_id");
            $weight = Util::getParamNotEmpty("weight");
            $record_day = Util::getParamNotEmpty("record_day");

            if(strlen($record_day) <=10 )
                $record_day = $record_day." 00:00:00";



            //yanzheng

            $user = UcUser::model()->findByPK($user_id);
            Util::checkExistAndNotDelete($user);

            //info


            $addflag = false;

             $obj  = UcWeight::model()->find("user_id=:user_id and record_day=:record_day ",
                         array(":user_id" => $user_id,":record_day" => $record_day ));

            if(empty($obj)==true)
            {
                //添加
                $obj = new UcWeight();
                Util::initObjData($obj);

                $obj->user_id = $user_id;
                $obj->record_day = $record_day;

                $addflag = true;

            }






            $obj->name = $user->name;
            $obj->weight = $weight;
            $obj->target_weight = $user->target_weight;



            Util::saveObjData($obj);


            if($addflag == true)
            {
                $title = "减肥－第三迭代－7-27(".$user->name." 更新体重:".$weight."kg)";
                $List = UcUser::model()->findAll();

                for($i=0;$i<count($List);$i++)
                {
                    $email = $List[$i]->email;

                    if($email != "0")
                        UserController::sendEmail($email,$title);
                }

            }


            //返回数据
            Util::responseMsg(MsgConst::RETURN_SUCCESS);


        } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
    * 获取列表分页
    *
    */
    public function actionGetWeightListPaging()
    {

        try {
            //参数验证

            //检测
            //$user_id = SessionService::getUserIDBySessionid();


            $searchsql = Util::initSearchSql();
            $searchsql = Util::getSerarchStr($searchsql,"user_id","user_id");


            //获取count
            $totalcount = UcWeight ::model()->count($searchsql);

                //排序
                $searchsql = $searchsql . " order by record_day  desc";

                //加上分页控制
                $searchsql = Util::addLimitSql($searchsql);

                //获取list
                $list = UcWeight ::model()->findAll($searchsql);


                Util::responseList($totalcount, $list);

            } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }


    }

    /*
    * 获取列表
    *
    */
    public function actionGetNewWeightList()
    {
        try {
            //参数验证

            //检测
           // $user_id = SessionService::getUserIDBySessionid();


            $datelist = UserController::getDateList();





           $return_array = array();

            $searchsql = Util::initSearchSql();
            $userlist =  UcUser::model()->findAll($searchsql);

            //插入用户

            for($i=0;$i<count($userlist);$i++)
            {
                $user = $userlist[$i];

                $user = UserController::clacUser($user);

                //体重列表

                $wlist = array();


                $cobj = 0;

                $count = 0;

                for($t=0;$t<count($datelist);$t++)
                {
                    $date = $datelist[$t]["record_day"];
                    $wobj = UserController::getWeightObj($user->user_id,$date);

                    if($wobj !=null)
                    {
                        if($count == 0)
                        {



                        }
                        else
                        {
                            $cha = number_format( ($wobj->weight - $cobj->weight), 1, '.', '');

                            $wobj->weight_diff = $cha;


                        }

                        $cobj = $wobj;

                        $count++;

                    }
                    else
                    {
                        $wobj  = new UcWeight();

                        $wobj->record_day = $date;
                        $wobj->id = -1;
                    }


                    array_push($wlist,$wobj);
                }

                $user->weight_list = $wlist;

                array_push($return_array,$user);
            }


                //返回数据
                //Util::responseList(count($list), $list);
             Util::responseObj($return_array);


            } catch (Exception $e) {
            Util::responseErrorMsg($e->getMessage());

        }
    }

    /*
    *
    *
    */
    public static function  clacUser($user)
    {
        $oldest_weight = UserController::getOldestWeight($user->user_id);
        $newest_weight = UserController::getNewsetWeight($user->user_id);

        //体重差（最近－最老）
        $user->weight_diff = number_format( ($newest_weight-$oldest_weight), 1, '.', '');


        //target_weight_diff 目标减重（最老－目标）

        $user->target_weight_diff =  number_format( ( $oldest_weight-$user->target_weight), 1, '.', '');


        //distance_to_target 离目标（最近－目标）

        $user->distance_to_target = number_format( ( $newest_weight-$user->target_weight), 1, '.', '');



        return $user;



    }

    /*
    *  获取用户最新一次体重
    *
    */
    public static function getNewsetWeight($user_id)
    {
        $sql = Util::initSearchSql();
        $sql = Util::getSerarchStrAdd($sql,"user_id",$user_id);

        $sql = $sql . " and record_day >= '2016-08-25 00:00:00' order by record_day  desc";
        $obj = UcWeight::model()->find($sql);

        if(empty($obj)==true)
            return 0;

        return $obj->weight;


    }

    /*
    *  获取用户最老一次体重
    *
    */
    public static function getOldestWeight($user_id)
    {
        $sql = Util::initSearchSql();
        $sql = Util::getSerarchStrAdd($sql,"user_id",$user_id);

        $sql = $sql . " and record_day >= '2016-08-25 00:00:00'  order by record_day  asc";
        $obj = UcWeight::model()->find($sql);

        if(empty($obj)==true)
            return 0;

        return $obj->weight;


    }

    /*
    * 获取list
    *
    */
    public static function getDateList()
    {





        //事务开始
        $connection = Yii::app()->db;

        $sql = "select DISTINCT(record_day) as record_day  from uc_weight where record_day >= '2016-08-25 00:00:00' ORDER BY record_day asc ";

        $command = $connection->createCommand($sql);

        $result = $command->queryAll();

        return $result;


    }


    /*
    *
    *
    */
    public static function getWeightObj($user_id,$date)
    {
        $sql = Util::initSearchSql();
        $sql = Util::getSerarchStrAdd($sql,"user_id",$user_id);
        $sql = Util::getSerarchStrAdd($sql,"record_day",$date);

       // echo $sql;
        $obj = UcWeight::model()->find($sql);

        if(empty($obj)==true)
            return null;

        return $obj;



    }

    /*
    * 添加
    *
    */
    public function actionSendEmalTest()
    {
        $email = "yhuang2@statestreet.com";

        $title = "减肥－第三迭代－7-27)";

        UserController::sendEmail($email,$title);


    }

    /*
    *
    *
    */
    public static function sendEmail($email,$title)
    {
        ini_set('date.timezone','Asia/Shanghai');
        $mail = new PHPMailer(); //实例化
        $mail->IsSMTP(); // 启用SMTP
        //$mail->Host = "smtp.qq.com"; //SMTP服务器 这里以新浪邮箱为例子
        $mail->Host = "smtp.qq.com"; //SMTP服务器 这里以新浪邮箱为例子
        $mail->Port = 25;  //邮件发送端口
        $mail->SMTPAuth   = true;  //启用SMTP认证
        $mail->CharSet  = "UTF-8"; //字符集
        $mail->Encoding = "base64"; //编码方式
        $mail->Username = "504301263@qq.com";  //你的邮箱
        $mail->Password = "Sigrid880822";  //你的密码
       // $mail->Subject = "减肥－第三迭代－7-27"; //邮件标题
        $mail->Subject = $title; //邮件标题
        $mail->From = "504301263@qq.com";  //发件人地址（也就是你的邮箱）
        $mail->FromName = "小黄瘦的刚刚好";  //发件人姓名
        $address = $email;//收件人email
        $mail->AddAddress($address, "某某人");//添加收件人地址，昵称
//$mail->AddAttachment("test,zip","重命名附件.zip"); // 添加附件,并重命名
        $mail->IsHTML(true); //支持html格式内容
        $mail->Body = "减肥内容更新 <br/> <iframe src=\"http://120.27.141.216:3107/\" style=\"width:100%; height:800px;\" />"; //邮件内容
//发送
        if(!$mail->Send()) {
           // echo "fail: " . $mail->ErrorInfo;
        } else {
          //  echo "ok";

        }


    }


}